package com.thrift.server.annotation;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 何锦涛--CodeSleep
 * @since 2022/9/11 18:11
 */
@Component
public class ThriftServerPostProcess implements BeanPostProcessor {

    // 单端口，多服务，嵌套 Map 的 key 表示服务名，value 表示实体名称
    public static final Map<Integer, Map<String, Object>> serviceMap = new HashMap<>(64);

    // 将所有被 @ThriftServer 修饰的类的 Bean 放到一个 Map 里，便于后续处理。
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        ThriftServer anno = bean.getClass().getAnnotation(ThriftServer.class);
        if (anno != null) {
            int port = anno.port();
            String serviceName = anno.serviceName();
            Map<String, Object> serviceContentMap = this.serviceMap.get(port);
            if (serviceContentMap == null)
                serviceContentMap = new HashMap<>();
            serviceContentMap.put(serviceName, bean);
            this.serviceMap.put(port, serviceContentMap);
        }
        return bean;
    }
}
